/**
 * 阿有 email:37798955@qq.com
 * 2017-11
 */
//fmt='yyyy-MM-dd hh:mm:ss'

var MYMODEL = null;

Date.prototype.addDays = function(days) {
	var date = new Date(this);
	date.setDate(date.getDate() + days);
	return date;
}
Date.prototype.addMonths = function(mons) {
	var date = new Date(this);
	date.setMonth(date.getMonth() + mons);
	return date;
}

Date.prototype.Format = function(fmt) {
	if(fmt == null || fmt == '')
		fmt = 'yyyy-MM-dd hh:mm:ss'
	var o = {
		"M+": this.getMonth() + 1, //月 
		"d+": this.getDate(), //日 
		"h+": this.getHours(), //时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒 
	};
	if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

function addmonnum(monnum, num) {
	var ym = new Number(monnum)
	var y = parseInt(ym / 100); //2017
	var m = ym % 100; //09
	var cnt = parseInt(num / 12);
	var mnt = num % 12;
	y = y + cnt;
	if(mnt < 0) {
		y = y - 1;
		m = m + (12 + mnt);
	} else {
		m = m + mnt;
	}
	if(m > 12) {
		y = y + 1;
		m -= 12;
	}
	return(y * 100 + m).toString();
}

function round2(number, fractiondigits) {
	with(Math) {
		return round(number * pow(10, fractiondigits)) / pow(10, fractiondigits);
	}
}
var _IS = new(function() {
	var gettype = Object.prototype.toString;
	this.isMap = function(o) {
		return gettype.call(o) == "[object Object]";
	}
	this.isArray = function(o) {
		return gettype.call(o) == "[object Array]";
	}
	this.isFun = function(o) {
		return gettype.call(o) == "[object Function]";
	}
	this.isNULL = function(o) {
		return gettype.call(o) == "[object Null]";
	}
	this.isUndefined = function(o) {
		return gettype.call(o) == "[object Undefined]";
	}
	this.isNum = function(o) {
		return gettype.call(o) == "[object Number]";
	}
	this.isString = function(o) {
		return gettype.call(o) == "[object String]";
	}
	this.isBool = function(o) {
		return gettype.call(o) == "[object Boolean]";
	}
	this.isEmptyMap = function(e) {
		for(var t in e)
			return false;
		return true
	}
	this.isEmptyString = function(str) {
		if(str == null || str == '')
			return true
		else
			return false
	}
	this.isEmptyArray = function(arr) {
		if(this.isArray(arr) || arr.length == 0)
			return true
		else
			return false
	}
})();

var _FF = new(function() {
	this.putV = function(targetid, obj) {
		tag = document.getElementById(targetid)
		if(tag == null)
			return;
		if(tag.tagName == "INPUT" || tag.tagName == "TEXTAREA") {
			tag.value = obj;
		} else if(tag.tagName == "DIV" || tag.tagName == "SPAN") {
			tag.innerHTML = obj;
		}
	}
	//只对数值有用
	this.getN = function(targetid, def) {
		var o = this.getV(targetid);
		var i = Number(o);
		if(isNaN(i)) {
			if(isNaN(def)) {
				return 0;
			} else {
				return def;
			}
		}
		return i;
	}
	this.getV = function(targetid) {
		tag = document.getElementById(targetid);
		if(tag == null)
			return null;
		var obj = '';
		if(tag.tagName == "INPUT" || tag.tagName == "TEXTAREA") {
			obj = tag.value
		} else if(tag.tagName == "DIV") {
			obj = tag.innerHTML
		}

		return obj;
	}
	this.ToM = function(value, arr, kv) {
		if(!_IS.isArray(arr)) return null;
		var fis = ['text', 'value']
		if(kv) {
			fis = kv.split(',')
		}
		for(var i = 0; i < arr.length; i++) {
			if(arr[i].value == value) {
				var obj = {}
				obj.text = arr[i][fis[0]]
				obj.value = arr[i][fis[1]]
				return obj;
			}
		}
	}
	this.putM = function(targetid, obj) {
		//console.log(JSON.stringify(obj))
		tag = document.getElementById(targetid)
		if(tag == null)
			return;
		if(obj == null)
			obj = {
				text: null,
				value: null
			};
		if(tag.tagName == "INPUT" || tag.tagName == "TEXTAREA") {
			tag.value = obj.text;
		} else if(tag.tagName == "DIV") {
			tag.innerHTML = obj.text;
		}
		tag.extenddata = obj.value
	}
	this.getM = function(targetid) {
		var obj = {
			text: null,
			value: null
		};
		tag = document.getElementById(targetid);
		if(tag == null)
			return obj;
		if(tag.tagName == "INPUT" || tag.tagName == "TEXTAREA") {
			obj.text = tag.value
		} else if(tag.tagName == "DIV") {
			obj.text = tag.innerHTML
		}
		obj.value = tag.extenddata
		return obj;
	}
})();

function trim(x) {
	return x.replace(/^\s+|\s+$/gm, '');
}
////时间戳转日期
//Date.prototype.getLocalTime = function(lt) {
//	return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
//}
////日期转时间戳
//Date.prototype.setLocalTime = function(datestr) {
//	return(new Date(datestr)).getTime() / 1000;
//}

//var oldTime = (new Date("2015/06/23 08:00:20")).getTime() / 1000;

function getGuid() {
	var d = new Date().getTime();
	var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = (d + Math.random() * 16) % 16 | 0;
		d = Math.floor(d / 16);
		return(c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
	});
	return uuid;
}

function clone(obj, attrs) {
	if(null == obj || "object" != typeof obj) return obj;
	if(obj instanceof Date) {
		var copy = new Date();
		copy.setTime(obj.getTime());
		return copy;
	}
	if(obj instanceof Array) {
		var copy = [];
		for(i = 0; i < obj.length; ++i) {
			copy.push(clone(obj[i]));
		}
		return copy;
	}
	if(obj instanceof Object) {
		var copy = {};
		if(attrs == null) {
			for(var attr in obj) {
				copy[attr] = clone(obj[attr]);
			}
		} else {
			for(var attr in attrs) {
				copy[attr] = clone(obj[attr]);
			}
		}
		return copy;
	}
	throw new Error("这个对象不支持拷贝.");
}
//数组去重,仅适用于单个列值得数组
function arrDistinct(arr) {
	var arr1 = []
	for(var i = 0; i < arr.length; i++) {
		var flag = true
		for(var j = 0; j < arr1.length; j++) {
			if(arr1[j] == arr[i]) {
				break;
				flag = false;
			}
		}
		if(flag)
			arr1.push(arr[i])
	}
	return arr1;
}
//数组编织对象
//实现 对数组的排序,分组,左联接
var _AW = new(
	function() {
		this.concat = function(a, b) {
			a = a | [];
			for(var i = 0; i < b.length; i++) {　　
				a.push(b[i]);
			}
			return a;
		}
		//orderby="field1%a,field3,field4%,field2%d" 4种格式 分别表示升序,升序,升序,降序
		//模仿select order by 功能
		this.sort = function(arr, orderby) {
			if(!(arr instanceof Array)) return null;
			var sp = orderby.split(',')
			for(var i = sp.length - 1; i >= 0; i--) {
				var j = sp[i].indexOf('%');
				var field = null;
				var hz = null
				if(j > 0) {
					field = sp[i].slice(0, j);
					hz = sp[i].slice(j);
				} else {
					field = sp[i].slice(0)
				}
				if(j > 0 && (hz == '%d' || hz == '%D')) {
					arr = arr.sort(sortcompare(field, 'd')) //降序排列			
				} else {
					arr = arr.sort(sortcompare(field)) //升序排列
				}
			}
			return arr;
		}
		this.move = function(arr1, i, n) {
			var a = arr1[i]
			var j = i + n
			j = j < 0 ? 0 : j;
			if(arr1[i]) {
				arr1.splice(i, 1);
			}
			arr1.splice(j, 0, a);
			return arr1;
		}
		//私有函数 type==null||type==''||type=='a' 
		//升序排列 否则 =='d'倒叙排列
		function sortcompare(prop, type) {
			return function(obj1, obj2) {
				var val1 = obj1[prop];
				var val2 = obj2[prop];
				if(!isNaN(Number(val1)) && !isNaN(Number(val2))) {
					val1 = Number(val1);
					val2 = Number(val2);
				}
				var r = 0;
				if(val1 < val2) {
					r = -1;
				} else if(val1 > val2) {
					r = 1;
				}
				if(type == 'd') {
					return 0 - r;
				} else
					return r;
			}
		}

		//内联接 arr1 主表 ,arr2 子表, joins 连接字段 "字段1=字段1,字段2=字段2"
		//模仿select left join 功能
		this.innerjoin = function(arr1, arr2, joinstr) {
			var a = []
			var b = []
			var joins = joinstr.split(",")
			for(var k = 0; k < joins.length; k++) {
				var obj = joins[k].split('=')
				if(obj.length == 2) {
					a.push(obj[0])
					b.push(obj[1])
				}
			}
			var arr = [];
			for(var i = 0; i < arr1.length; i++) {
				var obj1 = arr1[i]
				for(var j = 0; j < arr2.length; j++) {
					var obj2 = arr2[j]
					var flag = 1;
					for(var k = 0; k < a.length; k++) {
						if(obj1[a[k]] != obj2[b[k]]) {
							flag = 0;
							break;
						}
					}
					if(flag == 1) {
						var obj = mergeObj(obj1, obj2)
						arr.push(obj)
					}
				}
			}
			return arr;
		}
		//如果两张表的字段相同必须提前select
		//左联接 arr1 主表 ,arr2 子表, joins 连接字段 "字段1=字段1,字段2=字段2"
		this.leftjoin = function(arr1, arr2, joinstr) {
			var a = []
			var b = []
			var joins = joinstr.split(",")
			//拆解 on 字段1=字段2,字段1=字段2,字段1=字段2
			for(var k = 0; k < joins.length; k++) {
				var obj = joins[k].split('=')
				if(obj.length == 2) {
					a.push(obj[0])
					b.push(obj[1])
				}
			}
			var arr = [];
			for(var i = 0; i < arr1.length; i++) {
				var obj1 = arr1[i]
				var neq = true; //假设不会匹配到,如果匹配到 =false
				for(var j = 0; j < arr2.length; j++) {
					var obj2 = arr2[j]
					var flag = 1;
					for(var k = 0; k < a.length; k++) { //所有条件都满足
						if(obj1[a[k]] != obj2[b[k]]) {
							flag = 0; //有一个条件不满足
							break;
						}
					}
					if(flag == 1) {
						var obj = mergeObj(obj1, obj2)
						arr.push(obj)
						neq = false
					}

				}
				if(neq)
					arr.push(obj1);
			}
			return arr;
		}
		//合并o1和o2 生成新的对象,可以只选择抽取o1和o2中的部分字段
		function mergeObj(o1, o2, o1fields, o2fields) {
			var fis = null;
			if(o1fields)
				fis = o1fields.split(',')
			var n1 = clone(o1, fis);
			if(o2fields == null) {
				for(var key in o2) {
					n1[key] = o2[key]
				}
			} else {
				var fis2 = o1fields.split(',')
				for(var key in fis2) {
					n1[key] = o2[key]
				}
			}
			return n1;
		}
		//arr 表示 待分组的数据
		//fields 表示去重的字段
		//根据fieldstr 对数组中的对象进行去重
		//模仿select distinct 功能
		this.distinct = function(arr, fieldstr) {
			var arr1 = []
			var fields = fieldstr.split(',')
			for(var i = 0; i < arr.length; i++) {
				var obj1 = arr[i]
				var flag1 = 1
				//console.log( arr1.length)
				for(var j = 0; j < arr1.length; j++) {
					var obj2 = arr1[j]
					if(equalprop(obj1, obj2, fields)) { //如果属性值相同
						flag1 = 0
						break;
					} else {
						continue;
					}
				}
				if(flag1 == 1)
					arr1.push(section(obj1, fields))
			}
			return arr1;
		}
		//根据属性截取对象的部分属性 生成新的对象
		function section(object, cols) {
			var n1 = {}
			var props = null
			if(cols == null || cols == '') return object;
			if(cols instanceof String)
				props = cols.split(',')
			else
				props = cols
			for(var i = 0; i < props.length; i++) {
				n1[props[i]] = object[props[i]]
			}
			return n1

		}
		//groupcols= group by 后面的字段
		//countcols="field1","field2"..，待统计的之短
		//模仿group by count 功能
		this.groupby = function(tarr, groupcols, countcols) {
			var arr = this.sort(tarr, groupcols) //先排序
			//		for(var i in arr) {
			//			console.log(JSON.stringify(arr[i]))
			//		}
			var arr1 = [] //
			var fields = groupcols.split(',')
			var cols = countcols.split(',') //统计字段
			var ob1 = null;
			for(var i = 0; i < arr.length; i++) {
				var obj1 = arr[i]
				var flag1 = 1 //分组标志
				//console.log( arr1.length)
				for(var j = 0; j < arr1.length; j++) {
					var obj2 = arr1[j]
					if(equalprop(obj1, obj2, fields)) {
						flag1 = 0 //维值相等 继续累加
						for(var k = 0; k < cols.length; k++) {
							var col = cols[k]
							ob1[col]["count"]++;
							ob1[col]["lst"] = obj1[col];
							ob1[col]["sum"] += obj1[col];
							if(ob1[col]["min"] > obj1[col])
								ob1[col]["min"] = obj1[col]
							else if(ob1[col]["max"] < obj1[col])
								ob1[col]["max"] = obj1[col];
						}
					}
				}
				if(flag1 == 1) { //维值不等 新建一条
					ob1 = section(obj1, fields) //截取部分字段
					//对每个字段进行基本统计
					for(var k = 0; k < cols.length; k++) {
						var col = cols[k]
						ob1[col] = {}
						ob1[col]["count"] = 1;
						ob1[col]["sum"] = obj1[col];
						ob1[col]["min"] = obj1[col];
						ob1[col]["max"] = obj1[col];
						ob1[col]["fst"] = obj1[col];
						ob1[col]["lst"] = obj1[col];
					}
					arr1.push(ob1)
				}
			}
			return arr1;
		}

		//对比两个对象的特定属性 判断是否相等
		function equalprop(obj1, obj2, fields) {
			//console.log(fields)
			var flag = 1
			for(var i = 0; i < fields.length; i++) {
				var field = fields[i]
				if(obj1[field] == obj2[field]) {
					continue;
				} else {
					flag = 0;
					break;
				}
			}
			if(flag == 0) {
				return false;
			} else
				return true;
		}
		//fields="field1 field11,field2 field12,field3 field13" 把field1转为field11属性 ,其他一样
		//实现select as 功能.并截取指定列名,无指定不显示
		this.select = function(arr, fields) {
			var arr1 = [];
			for(var i = 0; i < arr.length; i++) {
				var n1 = this.selectcols(arr[i], fields);
				arr1.push(n1)
			}
			//console.log("n1"+JSON.stringify(arr1));
			return arr1;
		}
		this.selectcols = function(rc, select) {
			//console.log("selectcols::"+select);
			if(select == null || select == '') return rc;
			var keys = select.split(',')
			var ar = [] //原字段数组
			var br = [] //新列名数组
			//分解老新列名
			for(var i = 0; i < keys.length; i++) {
				var astr = null;
				if(keys[i].indexOf(':') > -1)
					astr = keys[i].split(':');
				else if(keys[i].indexOf(' ') > -1)
					astr = keys[i].split(' ');
				else if(keys[i].indexOf(' as ') > -1)
					astr = keys[i].split(' as ');
				else
					astr = keys[i];

				if(astr == null) continue;
				if(_IS.isArray(astr)) {
					if(astr[0] in rc) {
						ar.push(astr[0]);
						br.push(astr[1]);
					}
				} else {
					if(astr in rc) {
						ar.push(astr);
						br.push(astr);
					}
				}

			}
			if(ar.length == 0) return;
			var n1 = {} //目标对象
			for(var j = 0; j < ar.length; j++) {
				n1[br[j]] = rc[ar[j]]
			}
			//console.log("n1"+JSON.stringify(n1));
			return n1;
		}

		this.getColList = function(arr, column, filter) {
			var arr1 = [] //目标数组
			if(arr.length == 0) return;
			if(column in arr[0]) {
				for(var i = 0; i < arr.length; i++) {
					var em = arr[i][column];
					if(filter) {
						em = filter(em)
					}
					arr1.push(em);
				}
			}
			return arr1;
		}

	}
);
var DSQL=new (
	function(){		
		//???? 保存到文本文件
		var dbpath='_doc/db/';
		var fi=new zdyfile();
		this.setItem=function(key,value){
			fi.writeFile(dbpath+key,JSON.stringify(value));
		}
		this.getItem=function(key,callback){
			fi.readData(dbpath+key,function(value){
				if (callback)
					callback(JSON.parse(value));
			},'utf-8');
		}
		
//		this.setItem=function (key, value) {
//			if(key) {
//				if(window.plus) {					
//					plus.storage.setItem(key, JSON.stringify(value));
//				} else {
//					window.localStorage[key] = JSON.stringify(value);
//				}
//			}
//		}
//		
//		this.getItem=function (key) {
//			if(key) {
//				var obj = null;
//				if(window.plus) {					
//					obj = plus.storage.getItem(key);
//				} else {
//					obj = window.localStorage[key];
//				}
//				if(obj)
//					return JSON.parse(obj);
//			}
//			return null;
//		}	
	}
);
/**
 * 邹老师的前端 数据存储器 V1.0 
 * qq:37798955@qq.com
 * @param {Object} tblname
 * @param {Object} model
 * @param {Object} idtype
 */
function XCDBHelp(tblname, model, idtype) {
	this._tableName = "";
	this._err = '';
	this._where = null;
	this._select = null;
	this._model = null;
	//this._rs = ''; //结果集合 不能定义 因为很多结果会冲突
	this._columns = [];
	this._idtype = 'G';
	this.limitBegin = 0; //从哪个位置开始读取
	this.limitLen = -1; //n=-1 读取所有，n>-1 读取n条
	var _backuppath = 'backup.f'; //备份文件
	//初始化数据库
	this.init = function(tblname, model, idtype) {
		this._tableName = tblname;

		if(model == null) {
			if(MYMODEL && (tblname in MYMODEL)) {
				model = MYMODEL[tblname]
				model['_idkey'] = ''; //唯一编号
				model['_datekey'] = ''; //自动时间分区
				model['_syschgdate'] = ''; //变更时间
				this._model = model;
			}
		}
		//console.log("573"+tblname+JSON.stringify(model));

		//this._rs = arr;

		//自增类型还是guid类型
		if(idtype == null)
			this._idtype = 'G'
		else
			this._idtype = idtype.toUpperCase();
	}
	if(tblname)
		this.init(tblname, model, idtype);

	function update(key) {
		//alert('zzz')
		
		DSQL.getItem('ALLTABLESTATUS',
		function(mydb){
			if(mydb == null) mydb = {};
			mydb[key] = new Date().Format();
			DSQL.setItem('ALLTABLESTATUS', mydb);
		});
		
	}

	function getLen() {
		if(window.plus)
			return plus.storage.getLength();
		else
			return window.localStorage.length;
	}

	function removeItem(key) {
		if(window.plus)
			plus.storage.removeItem(key);
		else
			window.localStorage.removeItem(key);
	}

	function key(index) {
		if(window.plus)
			plus.storage.key(index);
		else
			window.localStorage.key(index);
	}

	//结构KEYID:{tablename:id}
	function getAutoID(tableName, idtype) {
		var idmap = DSQL.getItem("KEYID"); //专门存放自增的keyid
		if(idmap == null)
			idmap = [];
		var oid = idmap[tableName];
		if(oid == null)
			oid = 0;
		var nid;
		//console.log(idtype)
		if(idtype == 'G') //init()
		{
			nid = getGuid();
			//console.log(nid)
		} else {
			nid = parseInt(oid) + 1;
			//console.log(nid)
		}

		idmap[tableName] = nid;
		DSQL.setItem("KEYID", idmap);
		return oid, nid;
	}

	this.onErr = function(tx, e) {
		this._err = e;
		console.log(e.message);
	}
	this.batchreplace = function(callback) {
		var sub = DSQL.getItem(this._tableName);
		if(callback)
			sub = callback(sub)
		DSQL.setItem(this._tableName, sub);
	}
	//模型：当前库和历史库
	//当前库表名=key，记录是[]
	//当前库表名为_datekey：表名=key，记录是[]
	//_idkey 和_datekey 是插件的关键属性 ，自定义属性不能用_开头
	//修改当前对象
	this.setObj = function(obj) {

		//console.log('214:' + obj._idkey)
		var sub = DSQL.getItem(this._tableName);
		if(_IS.isEmptyString(obj._idkey)) { //等于空时 自动赋值id
			obj._idkey = getAutoID(this._tableName, this._idtype);
		}
		//console.log('218:' + obj._idkey)
		obj._syschgdate = new Date().Format()
		if(sub == null)
			sub = {}
		delete sub[""];
		sub[obj._idkey] = obj;
		//console.log(this._tableName)
		//console.log(this._idtype )
		//log(obj)
		DSQL.setItem(this._tableName, sub);
		update(this._tableName);
		return obj._idkey
	}
	this.delObjById = function(id) {
		var sub = DSQL.getItem(this._tableName);
		delete sub[id];
		DSQL.setItem(this._tableName, sub);
	}
	this.clear = function() {
		DSQL.setItem(this._tableName, {});
	}
	this.setList = function(rs) {
		for(i in rs) {
			this.setObj(rs[i])
		}
	}
	//修改历史对象
	function setHisObj(obj) {
		//(new Date()).format('yyyyMM')
		var key = obj._datekey + ":" + this._tableName;
		var sub = DSQL.getItem(key);
		obj._syschgdate = new date().Format()
		sub[obj._idkey] = obj;
		update(obj._idkey);
		DSQL.setItem(key, sub);
	}
	this.setHisList = function(rs) {
		for(i in rs) {
			setHisObj(rs[i])
		}
	}
	//移动
	this.mov2His = function(obj) {
		getObj(obj)
		setHisObj(obj)
	}

	function getListByIDs(tablename, idkeys) {
		var arr = []
		var sub = DSQL.getItem(tablename); //sub={} or map	
		//console.log('getListByIDs')
		//console.log(tablename)
		//log(sub)
		var key;
		if(sub == null) return null;
		if(idkeys instanceof Array && idkeys.length > 0) {
			for(i in idkeys) {
				key = idkeys[i]
				if(sub.hasOwnProperty(key))
					arr.push(sub[key]);
			}
			//console.log("cccc"+key+sub[key])
		} else if(typeof(idkeys) == 'string') {

			if(sub.hasOwnProperty(idkeys))
				//arr[idkeys]=sub[idkeys];
				arr.push(sub[idkeys]);
		}
		return arr;
	}
	//通过id得到对象
	this.getObjByID = function(id) {
		if(id == null) return null;
		var objs = getListByIDs(this._tableName, id.toString())
		if(objs == null) return null;
		if(objs.length > 0)
			return objs[0];
		return null;
	}
	//通过id得到对象
	this.getListByID = function(ids) {
		return getListByIDs(this._tableName, ids)
	}
	//参数格式： datekey:"";ids:[ids]
	this.getHisListByID = function(datekey, ids) {
		var key = datekey + ":" + this._tableName;
		return getListByIDs(key, ids)
	}
	//通过查询条件筛选内部数据得到对象
	this.getList = function(callback) {
		var sub = DSQL.getItem(this._tableName);
		return this.reduces(sub, callback);
	}
	//通过查询条件得到对象
	this.getHisList = function(datekey) {
		var key = datekey + ":" + this._tableName;
		var sub = DSQL.getItem(key); //[]记录集合
		return this.reduces(sub);
	}

	this.where = function(where) {
		this._where = where;
		return this;
	}
	this.select = function(selectsql) {
		this._select = selectsql;
		return this;
	}
	//限定记录列表区间
	this.limit = function(begin, len) {
		this.limitBegin = begin;
		this.limitLen = len;
		return this;
	}

	//对外部的数据进行筛选
	//rs=map
	this.reduces = function(rs, callback) {
		//if(this._where == null) return rs;
		//		/log(this._where,'jsondb.js647:')
		//console.log(JSON.stringify(this._where))
		var newrs = [];
		//
		if(callback && callback.ini)
			callback.ini();
		if(rs) {
			//for(var i  in rs) {
			var begin = 0;
			var len = 0;
			this.limitBegin = this.limitBegin | 0;
			if(limitBegin > rs.length) {
				this.limitBegin = 0;
			} else {
				begin = this.limitBegin;
			}
			if((!this.limitLen) || this.limitLen < 0 || begin + this.limitLen > rs.length) {
				this.limitLen = rs.length - begin;
			}
			len = this.limitLen;
			for(var i = begin; i < len; i++) {
				if(rs[i]) {
					//console.log("ggg0"+i+JSON.stringify(rs[i]))
					//console.log("ggg0"+rs[i])
					//console.log(this._select);				
					var rc = reduce(rs[i], this._where);
					if(rc) {
						newrs.push(_AW.selectcols(rc, this._select))
						if(callback && callback.ing)
							callback.each(rc, i);
					}
				}
			}
		}
		if(callback && callback.finish)
			callback.finish();
		//console.log("ggg1")
		return newrs;
	}

	//key ='field(','field)','field[','field]','field=','field%','or'
	//,'field[%','field%]' 数组和map 不允许用特殊符号表示大小比较和模糊匹配
	//每条记录的属性与条件进行判断
	function reduce(rc, whereobj) {
		if(rc instanceof Array && rc.length > 0) {
			return null;
		}
		if(whereobj == null) {
			return rc;
		}
		if(whereobj instanceof Array && whereobj.length > 0) {
			for(var i = 0; i < whereobj.length; i++) {
				//for(var i in whereobj) {
				//console.log(JSON.stringify(whereobj[i]))
				var r = reduce(rc, whereobj[i]);
				if(r != null) return r;
			}
			//console.log("dd "+JSON.stringify(whereobj))
			return null;
		} else {
			if(typeof(whereobj) === 'string') { //不支持 string 类型的条件
				return rc;
			}
			for(var key in whereobj) {
				var v = whereobj[key];

				if(v == null || v === '') continue; //如果查询的值为空跳过
				//	console.log(key +' '+v+' '+rcv)

				if(key == "or") {
					//此时的wvalue=[条件]
					if(v instanceof Array && v.length > 0)
						return reduce(rc, v);
				} else {
					var m = '=';
					var n = 0;
					if((n = key.indexOf('=')) > 0)
						m = '=';
					else if((n = key.indexOf('(')) > 0)
						m = '(';
					else if((n = key.indexOf(')')) > 0)
						m = ')';
					else if((n = key.indexOf('[%')) > 0)
						m = '[%';
					else if((n = key.indexOf('%]')) > 0)
						m = '%]';
					else if((n = key.indexOf('[')) > 0)
						m = '[';
					else if((n = key.indexOf(']')) > 0)
						m = ']';
					else if((n = key.indexOf('%')) > 0)
						m = '%';

					if(n == -1)
						n = key.length;

					key = key.slice(0, n).replace(/(^\s*)|(\s*$)/g, "");
					var rcv = rc[key];
					if(_IS.isArray(rcv) || _IS.isMap(rcv)) continue; //如果是数组或者map类型跳过

					//console.log(key+' '+rcv+m+' '+v)

					if(typeof(rcv) == "undefined") {
						return null;
					} else if(typeof(rcv) == 'string') {
						//console.log(m + ' '+typeof(rcv) +' ' + rcv+' '+v+rcv.indexOf(v) )
						if((m == '=' && rcv == v) ||
							(m == '%' && rcv.indexOf(v) > -1) ||
							(m == '[%' && rcv.indexOf(v) == 0) ||
							(m == '%]' && rcv.slice(-v.length) == v) ||
							(m == '(' && rcv > v) || (m == ')' && rcv < v) ||
							(m == '[' && rcv >= v) || (m == ']' && rcv <= v)) {
							continue;
						} else {
							return null;
						}
					} else if(typeof(rcv) === 'number') {
						if((m == '=' && rcv == v) || (m == '(' && rcv > v) ||
							(m == ')' && rcv < v) || (m == '[' && rcv >= v) ||
							(m == ']' && rcv <= v)) {
							//console.log(key+' '+rcv+' '+m+' '+v)
							continue;
						} else {
							return null;
						}
					} else if(_IS.isBool(rcv)) {
						if((m == '=' && rcv == v)) {
							continue;
						} else {
							return null;
						}
					} else {
						console.log('条件表达式错误请检查')
						continue;
					}
				}
			}
			//console.log('ok'+key)
			return rc;
		}
	}
}
//model 在开始的时候插入createdb.html
function hasClass(obj, cls) {
	var obj_class = obj.className, //获取 class 内容.
		obj_class_lst = obj_class.split(/\s+/); //通过split空字符将cls转换成数组.
	x = 0;
	for(x in obj_class_lst) {
		if(obj_class_lst[x] == cls) { //循环数组, 判断是否包含cls
			return true;
		}
	}
	return false;
}

function createMmdl() {
	var obj = {
		_tableName: "",
		_rs: [{
			_data: {},
			_where: {}
		}]
	};
	return obj;
}

function createSmdl() {
	var obj = {
		_tableName: "",
		_rs: [{
			_data: {},
			_where: {}
		}]
	};
	return obj;
}
//测试打印json对象
function log(data, note) {
	var s = JSON.stringify(data);
	if(note == null)
		console.log(s)
	else
		console.log(note + ' ' + s)
}
//测试打印map对象
function printmap(map) {
	for(var i in map) {
		console.log(JSON.stringify(map[i]));
	}
}
//-----------------防止转拼音
//////////////////下拉与数据有关 所以放在这里

var PAGESIZE = 30;
var CURMON = new Date().Format('yyyyMM')
/*
examples:
var db=createdb();
db.init('channel_list',[{name:'id',type:'integer primary key autoincrement'},{name:'name',type:'text'},{name:'link',type:'text'},{name:'cover',type:'text'},{name:'updatetime',type:'integer'},{name:'orders',type:'integer'}]);
db.init('feed_list',[{name:'parentid',type:'integer'},{name:'feed',type:'text'}]);
db.where({name:'aa'}).getData(function(result){
  console.log(result);//result为Array
});
db.where({name:'aa'}).deleteData(function(result){
  console.log(result[0]);//删除条数
});
db.where({name:'bb'}).saveObj({link:'jj'},function(result){
  console.log(result);//影响条数
})
})
*/